package com.saver.view.item;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Highlight;
import com.github.mikephil.charting.utils.ValueFormatter;
import com.saver.R;
import com.saver.core.persistence.TransaccionSQLite;
import com.saver.core.util.Constantes;
import com.saver.core.util.DateUtil;
import com.saver.core.util.ItemUtil;
import com.saver.view.MainActivity;
import com.saver.view.formatter.NumberValueFormatter;
import com.saver.view.gui.FragmentSupport;
import com.saver.view.model.FragmentModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

public class BarChartFragment extends ChartItemFragment implements OnChartValueSelectedListener {

    BarChart chart;

    public static BarChartFragment instanceOf(Bundle args) {
        BarChartFragment fragment = new BarChartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_item_barchart, container, false);
        chart = (BarChart) view.findViewById(R.id.barchart);
        chart.setDescription("");
        chart.setDrawGridBackground(true);
        chart.setDrawBarShadow(false);
        chart.setOnChartValueSelectedListener(this);
        chart.setHighlightEnabled(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setTypeface(mTf);
        xAxis.setSpaceBetweenLabels(2);
        xAxis.setDrawGridLines(false);

        ValueFormatter custom = new NumberValueFormatter();

        YAxis yAxisLeft = chart.getAxisLeft();
//        yAxisLeft.setTypeface(mTf);
        yAxisLeft.setValueFormatter(custom);
        yAxisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        yAxisLeft.setLabelCount(10);
        yAxisLeft.setSpaceTop(10f);

        YAxis yAxisRight = chart.getAxisRight();
        yAxisRight.setDrawGridLines(false);
//        yAxisRight.setTypeface(mTf);
        yAxisRight.setLabelCount(10);
        yAxisRight.setValueFormatter(custom);
        yAxisRight.setSpaceTop(15f);

        mChartData = generateDataBar();
        chart.setData((BarData) mChartData);
        chart.animateY(700);
        chart.getData().setDrawValues(false);
        chart.getData().setValueFormatter(custom);

        Legend legend = chart.getLegend();
        legend.setEnabled(false);
        return view;
    }

    private BarData generateDataBar() {
        TransaccionSQLite transaccionSQLite = new TransaccionSQLite(this.getActivity());
        List<ItemUtil> listaTotales;
        FragmentModel model = (FragmentModel) getArguments().getSerializable("args");
        tipoConsulta = model.getTipoConsulta();
        anio = model.getCalendar().get(Calendar.YEAR);
        mes = model.getCalendar().get(Calendar.MONTH) + 1;

        if (tipoConsulta == Constantes.CONSULTA_X_ANIO) {
            listaTotales = transaccionSQLite.listarTotalesXAnios();
        } else if (tipoConsulta == Constantes.CONSULTA_X_MES) {
            listaTotales = transaccionSQLite.listarTotalesXMeses(anio);
        } else {
            listaTotales = transaccionSQLite.listarTotalesXDias(anio, mes);
        }

        int cnt = 1;
        ArrayList<BarEntry> entries = new ArrayList<BarEntry>();
        int i = 0;
        for (ItemUtil item : listaTotales) {
            entries.add(new BarEntry(item.getValor(), i, item));
            i++;
        }

        BarDataSet dataSet = new BarDataSet(entries, "" + cnt);
        dataSet.setBarSpacePercent(20f);
        int[] color = {Color.rgb(67, 184, 215)};
        dataSet.setColors(color);
        dataSet.setHighLightAlpha(255);
        if(listaTotales.isEmpty()){
        	return new BarData();
        }else{
        	return new BarData(getLabels(listaTotales, tipoConsulta), dataSet);
        }
    }

    private ArrayList<String> getLabels(List<ItemUtil> listaTotales, int tipoConsulta) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("MMM", Locale.getDefault());
        Calendar calendar;
        ArrayList<String> dataLabels = new ArrayList<String>();
        for (ItemUtil item : listaTotales) {
            if (tipoConsulta == Constantes.CONSULTA_X_MES) {
                calendar = new GregorianCalendar();
                calendar.set(Calendar.MONTH, Integer.parseInt(item.getDescripcion()) - 1);
                dataLabels.add(sdf1.format(calendar.getTime()).toUpperCase());
            } else {
                dataLabels.add(item.getDescripcion());
            }
        }
        return dataLabels;
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        FragmentModel currentModel = (FragmentModel) getArguments().getSerializable("args");
        Calendar calendar = DateUtil.CURRENT_DATE;
        calendar.setTimeInMillis(currentModel.getCalendar().getTimeInMillis());
        ItemUtil itemDate = (ItemUtil) e.getData();
        switch (currentModel.getTipoConsulta()) {
            case Constantes.CONSULTA_X_ANIO://año
                calendar.set(Calendar.YEAR, Integer.parseInt(itemDate.getDescripcion()));
                break;
            case Constantes.CONSULTA_X_MES://mes
                calendar.set(Calendar.MONTH, Integer.parseInt(itemDate.getDescripcion()) - 1);
                break;
            case Constantes.CONSULTA_X_DIA://dia
                calendar.set(Calendar.DATE, Integer.parseInt(itemDate.getDescripcion()));
                break;
        }
        FragmentModel model = new FragmentModel();
        model.setTipoGrafico(Constantes.TIPO_GRAFICO_LIST);
        model.setCalendar(calendar);
        model.setReferencia(DateUtil.FORMATO_GENERAL.format(calendar.getTime()));
        model.setTipoConsulta(currentModel.getTipoConsulta());
        Bundle bundle = new Bundle();
        bundle.putSerializable("args", model);
        FragmentSupport fragment = new ParentViewPagerFragment();
        fragment.setFragmentName("FRAGMENTO_REGISTRO");
        fragment.setPosition(1);
        fragment.setArguments(bundle);
        MainActivity.main().reemplazarFragmento(fragment);
    }

    @Override
    public void onNothingSelected() {
    }
}
